Java Method Overriding

In Java, if both the superclass and the subclass has the same method name with equal number of paramaters, then it is known as method overriding.

Example for method overriding

class Animal {
   public void Display() {
      System.out.println("I'm an animal");
   }
}

class Cat extends Animal {
   public void Display() {
      System.out.println("I am a cat.");
   }
}

class Main {
   public static void main(String[] args) {
      Cat cat = new Cat();
      cat.Display();
   }
}

On running the above program, it will display the following result.

I am a cat.

In the above example, the Animal class has a method Display(). The Animal class is then inherited by Cat class.

To override the behavior of Display() method in Animal class, we need to define Display() method in the Cat subclass.

Now when we create cat object for the Cat class, and try to access the Display() method, it will call the Display() method of the Cat class.

Some of the rules to be followed when using method overriding. They are

  • The method name of the superclass show be same as the method name of the subclass.
  • Both the methods in subclass and superclass should have the same number of parameters.
  • Method that is declared as static or final cannot be overridden.

Suppose, if we need to access the method that is in superclass in our subclass then we need to use super keyword and access that method.

Example for super keyword

class Animal {
   public void Display() {
      System.out.println("I'm an animal");
   }
}

class Cat extends Animal {
   public void Display() {
      super.Display();
      System.out.println("I am a cat.");
   }
}

class Main {
   public static void main(String[] args) {
      Cat cat = new Cat();
      cat.Display();
   }
}

We have modified the previous example. Here, we need to call the Display() method of Animal class inside the Display() method of Cat class.

To do this we have used super.Display() to call the superclass Display() method inside the Display() method of Cat class.

Executing the above program will display the result as

I'm an animal
I am a cat.

Things to be considered when trying to implement method overriding.

  • final method cannot be overridden.
  • static method cannot be overridden.
  • The name of the function and parameters should be same as the superclass.

Most Read